package cn.scau.server.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行 Swagger 请求
        if (request.getRequestURI().contains("/swagger-ui") ||
                request.getRequestURI().contains("/swagger-resources") ||
                request.getRequestURI().contains("/v2/api-docs") ||
                request.getRequestURI().contains("/webjars") ||
                request.getRequestURI().contains("/doc")) {
            return true;
        }

        // 检查用户是否已经登录
        if (MobileUserHolder.getEmpPermission() == null) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "User is not logged in");
            return false;
        }

        // 用户已登录，放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        MobileUserHolder.removeEmpPermission();
    }
}